#include "log.h"
#include "usart.h"
#include "user_shell.h"
#include "bsp_nandflash.h"
#include "stdio.h"
#include "string.h"
Shell shell;
char shellBuffer[512];

signed short shell_read(char *buff, unsigned short len) 
{
  HAL_UART_Receive(&SHELL_UART, (uint8_t *)buff, len, 0x00);
  return len;
}

signed short shell_write(char *buff, unsigned short len)
{
  HAL_UART_Transmit(&SHELL_UART, (uint8_t *)buff, len, 0xFF);
  return len;
}


void userShellInit(void)
{

    shell.write = shell_write;
    shell.read = shell_read;

    shellInit(&shell, shellBuffer, 512);
    HAL_UART_Receive_IT(&SHELL_UART, (uint8_t *)&shellChar, 1);

}

char shellChar;
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if(huart == &SHELL_UART)
  {
    shellHandler(&shell, shellChar);
    HAL_UART_Receive_IT(&SHELL_UART, (uint8_t *)&shellChar, 1);
  }
}

uint8_t nandFlashReadBuff[2048];

uint8_t readNandFlash(uint32_t sector)
{ 
  memset(nandFlashReadBuff,0,2048);

  NandFlash_ReadPages(nandFlashReadBuff, sector, 1);
  for(int i=0; i<2048; i++)
  {
    if(i % 32 == 0)
    {
      printf("\n\r");
    }
    printf("0x%02x ", nandFlashReadBuff[i]);
  }
}

SHELL_EXPORT_CMD(
SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),
readFlash, readNandFlash, read nandflash sector);


uint8_t eraseNandFlash(uint32_t sector)
{
  memset(nandFlashReadBuff,-1,2048);
  NandFlash_Write(nandFlashReadBuff, sector);
  readNandFlash(sector);
}

SHELL_EXPORT_CMD(
SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),
eraseFlash, eraseNandFlash, erase nandflash sector);

uint8_t clearNandFlash(uint32_t sector)
{
  memset(nandFlashReadBuff,0,2048);
  NandFlash_Write(nandFlashReadBuff, sector);
  readNandFlash(sector);
}

SHELL_EXPORT_CMD(
SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),
clearFlash, clearNandFlash, clear nandflash sector);

uint8_t eraseBlock(uint32_t sector)
{
  NandFlash_EraseBlock(sector);
}

SHELL_EXPORT_CMD(
SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),
eraseBlock, eraseBlock, Erase nandflash BLOCK);

uint8_t writeNandFlash(uint32_t sector)
{
  for(int i=0; i<2048; i++)
  { 
    nandFlashReadBuff[i] = i % 256;
  }
  nandFlashReadBuff[0] = 0x55;
  nandFlashReadBuff[2047] = 0xAA;

  NandFlash_Write(nandFlashReadBuff, sector);
  readNandFlash(sector);

}

SHELL_EXPORT_CMD(
SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC),
writeFlash, writeNandFlash, write nandflash sector);

